package com.zhou.common.operator.log.boot.starter;

import com.zhou.common.operator.log.core.OperateLogProperty;
import com.zhou.common.operator.log.core.resolver.ClientInfoResolver;
import com.zhou.common.operator.log.core.resolver.PrincipalResolver;
import com.zhou.common.operator.log.core.resolver.impl.DefaultClientInfoResolver;
import com.zhou.common.operator.log.core.resolver.impl.DefaultPrincipalResolver;
import com.zhou.common.operator.log.core.service.OperateLogStorageService;
import com.zhou.common.operator.log.storage.JdbcStorageService;
import com.zhou.common.operator.log.storage.api.RestApiStorgeService;
import com.zhou.common.operator.log.storage.api.feign.OperateLogFeignClient;
import com.zhou.common.operator.log.storage.mybatis.config.OperatorLogMybatisConfig;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;

@EnableConfigurationProperties({OperateLogProperty.class})
@ComponentScan(
        basePackages = {"com.zhou.common.operator.log.core"}
)
@Configuration
public class OperateLogCollectorConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public ClientInfoResolver defaultClientInfoResolver() {
        return new DefaultClientInfoResolver();
    }

    @Bean
    @ConditionalOnMissingBean
    public PrincipalResolver defaultPrincipalResolver() {
        return new DefaultPrincipalResolver();
    }

    @Bean
    @ConditionalOnProperty(
            name = {"szzz.operate.log.storage"},
            havingValue = "jdbc"
    )
    public OperateLogStorageService mysqlStorageService(OperateLogProperty properties, JdbcTemplate jdbcTemplate) {
        return new JdbcStorageService(properties, jdbcTemplate);
    }

    @ConditionalOnProperty(
            name = {"szzz.operate.log.storage"},
            havingValue = "mybatis",
            matchIfMissing = true
    )
    @Import({OperatorLogMybatisConfig.class})
    static class MybatisStorageServeiceConfiguration {

    }

    @Configuration
    @ConditionalOnProperty(
            name = {"szzz.operate.log.storage"},
            havingValue = "api"
    )
    @EnableFeignClients(
            basePackages = {"com.zhou.common.operator.log.storage.api"}
    )
    static class RestApiServeiceConfiguration {

        @Lazy
        @Bean
        public OperateLogStorageService apiStorageService(OperateLogProperty properties, ObjectProvider<OperateLogFeignClient> provider) {
            return new RestApiStorgeService(properties);
        }
    }

}

